﻿using Furion;
using Furion.DatabaseAccessor;
using Jiffy.Common.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Linq;
using System.Linq.Expressions;
using Yitter.IdGenerator;

namespace Jiffy.Core.Log
{
    [AppDbContext("LogConnection", DbProvider.MySql)]
    public class LogDbContext : AppDbContext<LogDbContext, LogDbContextLocator>, IModelBuilderFilter
    {
        public LogDbContext(DbContextOptions<LogDbContext> options) : base(options)
        {

            // 启用实体数据更改监听
            EnabledEntityChangedListener = true;

            // 忽略空值更新
            InsertOrUpdateIgnoreNullValues = true;
        }

        public void OnCreating(ModelBuilder modelBuilder, EntityTypeBuilder entityBuilder, DbContext dbContext, Type dbContextLocator)
        {
            // 假删除过滤器
            LambdaExpression expression = FakeDeleteQueryFilterExpression(entityBuilder);
            if (expression != null)
                entityBuilder.HasQueryFilter(expression);
        }

        /// <summary>
        /// 假删除过滤器
        /// </summary>
        /// <param name="entityBuilder"></param>        
        /// <param name="isDeletedKey"></param>
        /// <param name="filterValue"></param>
        /// <returns></returns>
        protected LambdaExpression FakeDeleteQueryFilterExpression(EntityTypeBuilder entityBuilder, string isDeletedKey = null, object filterValue = null)
        {
            isDeletedKey ??= "IsDeleted";
            IMutableEntityType metadata = entityBuilder.Metadata;

            Expression finialExpression = Expression.Constant(true);
            ParameterExpression parameterExpression = Expression.Parameter(metadata.ClrType, "u");

            // 假删除过滤器
            if (metadata.FindProperty(isDeletedKey) != null)
            {
                ConstantExpression constantExpression = Expression.Constant(isDeletedKey);
                ConstantExpression right = Expression.Constant(filterValue ?? false);
                var fakeDeleteQueryExpression = Expression.Equal(Expression.Call(typeof(EF), "Property", new Type[1]
                {
                    typeof(bool)
                }, parameterExpression, constantExpression), right);
                finialExpression = Expression.AndAlso(finialExpression, fakeDeleteQueryExpression);
            }

            return Expression.Lambda(finialExpression, parameterExpression);
        }

        /// <summary>
        /// 写入拦截
        /// </summary>
        /// <param name="eventData"></param>
        /// <param name="result"></param>
        protected override void SavingChangesEvent(DbContextEventData eventData, InterceptionResult<int> result)
        {
            // 获取所有已更改的实体
            var entities = eventData.Context.ChangeTracker.Entries()
                                    .Where(u => u.State == EntityState.Modified || u.State == EntityState.Deleted || u.State == EntityState.Added)
                                    .ToList();

            // 当前操作用户信息
            var userId = "-1";
            var userName = "系统";
            if (App.User != null)
            {
                userId = App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value;
                userName = App.User.FindFirst(ClaimConst.CLAINM_ACCOUNT)?.Value;
            }


            foreach (var entity in entities)
            {
                if (entity.Entity.GetType().IsSubclassOf(typeof(LogEntityT)))
                {
                    var obj = entity.Entity as LogEntityT;
                    if (entity.State == EntityState.Added)
                    {
                        obj.Id = YitIdHelper.NextId();
                        obj.CreatedTime = DateTimeOffset.Now;
                        if (!string.IsNullOrEmpty(userId))
                        {                            
                            //obj.CreatedUserId = long.Parse(userId);
                            //obj.CreatedUserName = userName;
                        }
                    }
                    else if (entity.State == EntityState.Modified)
                    {
                        //obj.UpdatedTime = DateTimeOffset.Now;
                        //obj.UpdatedUserId = long.Parse(userId);
                        //obj.UpdatedUserName = userName;
                    }
                }
            }
        }

        /// <summary>
        /// 配置懒加载 —— 暂未完成
        /// </summary>
        /// <param name="optionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //optionsBuilder.UseLazyLoadingProxies()
            //             .UseMySQL(DbProvider.GetConnectionString<LogDbContext>());

            base.OnConfiguring(optionsBuilder);
        }
    }
}